<template>
  <div>
    <div class="inline-form">
      <!-- 表单内容 -->
      <Form ref="form1" :model="form1" :rules="rules1" :label-width="120" style="display: block;">
        <FormItem prop="leaveType" label="请假类型:">
          <Select v-model="form1.leaveType" @on-change="leaveTypeChange" clearable>
            <Option v-for="item in leaveTypeList" :key="item.key" :value="item.key">{{item.value}}</Option>
          </Select>
          <div class="form-tip" v-if="leaveTypeShow">
            <Icon type="ios-alert-outline" size="24" />可用
            <span v-for="item in leaveTypeList" :key="item.key">
              <span v-if="item.key == form1.leaveType">{{item.value}}</span>
            </span>
            ：{{usableDay}}天
          </div>
        </FormItem>
        <Row>
          <i-col span="18">
            <FormItem prop="startDate" label="开始时间:">
              <DatePicker
                type="date"
                class="form-input-small"
                v-model="form1.startDate"
                placeholder="请选择日期"
                @on-change="calTime"
                :editable="false"
              ></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="startDatePeriod" :label-width="0">
              <Select v-model="form1.startDatePeriod" @on-change="calTime" clearable>
                <Option value="am">上午</Option>
                <Option value="pm">下午</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col span="18">
            <FormItem prop="endDate" label="结束时间:">
              <DatePicker
                type="date"
                class="form-input-small"
                v-model="form1.endDate"
                placeholder="请选择日期"
                @on-change="calTime"
                :editable="false"
              ></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem prop="endDatePeriod" :label-width="0">
              <Select v-model="form1.endDatePeriod" @on-change="calTime" clearable>
                <Option value="am">上午</Option>
                <Option value="pm">下午</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <FormItem prop="leaveTime" label="请假时间:">
          <i-input
            type="text"
            class="form-input-small"
            v-model="form1.leaveTime"
            disabled
            @on-change="checkLeaveTime()"
          >
            <div slot="suffix" style="line-height:32px;color:rgba(0,0,0,0.43)">天</div>
          </i-input>
        </FormItem>
        <FormItem prop="leaveReason" label="请假事由:">
          <i-input type="textarea" v-model="form1.leaveReason" :rows="4" placeholder="请输入"></i-input>
        </FormItem>
        <!-- 文件上传 -->
        <FormItem prop="leaveFile" label="说明附件:">
          <Uploadv
            multiple
            ref="upload"
            type="drag"
            :before-upload="handleUpload"
            :show-upload-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadFail"
            :headers="{
              Authorization:'',
            }"
            name="multipartFile"
            :data="{
              applyNo:'1'
            }"
            :action="action"
          >
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>点击或将文件拖拽到这里上传</p>
            <p style="color:rgba(0,0,0,0.43)">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</p>
          </Uploadv>
          <div v-for="(item, index) in file" :key="index">
            <div>
              <Icon type="md-attach" style="transform:rotate(90deg);" />
              &nbsp;{{ item.name }}
              <span @click="delectFile(item.keyID)" class="deleteFile">X</span>
            </div>
          </div>
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            style="width:74px"
            @click="handleSubmit('form1')"
            :loading="submitLoading"
          >提交</Button>
          <Button
            type="default"
            style="width:74px;margin-left:25px"
            @click="previousStep"
            v-if="previousStepShow"
          >上一步</Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
export default {
  props: {
    applyInfo: {
      type: String
    }
  },
  data() {
    const validateStartDate = (rule, value, callback) => {
      if (this.form1.startDate == "" || this.form1.endDate == "") {
      } else {
        this.$refs.form1.validateField("endDate");
        callback();
      }
      callback();
    };
    const validateEndDate = (rule, value, callback) => {
      if (this.form1.startDate == "" || this.form1.endDate == "") {
      } else if (
        this.form1.startDate.getTime() > this.form1.endDate.getTime()
      ) {
        callback(new Error("结束日期需大于等于开始时间"));
      }
      callback();
    };
    const validateLeaveTime = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入请假时间"));
      } else if (this.form1.leaveType == "" || this.form1.leaveType == null) {
        callback(new Error("请选择请假类型"));
      } else if (this.form1.leaveTime > this.usableDay) {
        callback(new Error("天数已超，不可进行此操作"));
      }
      callback();
    };
    return {
      form1: {
        leaveType: "",
        startDate: new Date(),
        startDatePeriod: "am",
        endDate: new Date(),
        endDatePeriod: "pm",
        leaveTime: "1",
        leaveReason: ""
      },
      rules1: {
        leaveType: [{ required: true, message: "请假类型不能为空" }],
        startDate: [
          { required: true, message: "开始时间不能为空" },
          { validator: validateStartDate, trigger: "blur" },
          { validator: validateStartDate, trigger: "change" }
        ],
        startDatePeriod: [{ required: true, message: "时段不能为空" }],
        endDate: [
          { required: true, message: "结束时间不能为空" },
          { validator: validateEndDate, trigger: "blur" },
          { validator: validateEndDate, trigger: "change" }
        ],
        endDatePeriod: [{ required: true, message: "时段不能为空" }],
        leaveTime: [
          { required: true, message: "请假时长不能为空" },
          { validator: validateLeaveTime, trigger: "change" }
        ]
      },
      leaveTypeList: [],
      leaveTypeValue: "",
      usableDay: "",
      file: [],
      deleteFiles: [],
      applyNo: "",
      previousStepShow: true,
      leaveTypeShow: false,
      fileIndex: 0,
      submitLoading: false,
      action: ""
    };
  },
  methods: {
    // 获取请假类型
    selectType() {
      this.api.selectType().then(res => {
        if (res.code == 200 && res.data != null) {
          this.leaveTypeList = res.data.data;
        }
      });
      // this.action = sessionStorage.getItem("userIp") + "scrm-uer/api/fileupload/up";
      this.action = "/scrm-gateway/scrm-uer/api/fileupload/up";
    },

    // 通过请假类型获取可用请假天数
    usableDays(detail) {
      let obj = {
        employeeNo: "1",
        detail: detail
      };
      this.api.residualVacation(obj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.usableDay = res.data;
          if (this.form1.leaveTime != "") {
            this.$refs.form1.validateField("leaveTime");
          }
        } else {
          this.usableDay = 9000000000000000000000000000;
        }
      });
    },

    // 重置表单
    handleReset(name) {
      this.$refs[name].resetFields();
    },

    // 请假时间计算
    calTime() {
      if (
        this.form1.startDate == "" ||
        this.form1.endDate == "" ||
        this.form1.startDatePeriod == "" ||
        this.form1.endDatePeriod == ""
      ) {
      } else {
        let newstartDate = new Date(this.form1.startDate);
        let newendDate = new Date(this.form1.endDate);
        let calTime = Math.ceil(
          (newendDate.getTime() - newstartDate.getTime()) / 86400000
        );
        let startP = this.form1.startDatePeriod;
        let endP = this.form1.endDatePeriod;

        if (calTime >= 0) {
          if (startP == endP) {
            calTime += 0.5;
          } else if (startP == "am" && endP == "pm") {
            calTime += 1;
          } else if (startP == "pm" && endP == "am") {
            // 同一天的上下午校验
            if (calTime == 0) {
              if (startP == "pm" && endP == "am") {
                this.$Message.error({
                  content:
                    "开始时间与结束时间相同时，开始时间为下午时，结束时间不能为上午",
                  duration: 3
                });
                this.form1.endDatePeriod = null;
              }
            }
          }
          this.checkLeaveTime();
        }
      }
    },

    // 判断请假时间是否小于等于可用天数
    checkLeaveTime() {
      let dat = new Date(this.form1.startDate).toJSON();
      let date = new Date(+new Date(dat) + 8 * 3600 * 1000).toISOString();
      let d1 = new Date(this.form1.endDate).toJSON();
      let date1 = new Date(+new Date(d1) + 8 * 3600 * 1000).toISOString();
      let obj = {
        applyType: "1",
        startTime: date,
        endTime: date1,
        startTimeSolt: this.form1.startDatePeriod,
        endTimeSolt: this.form1.endDatePeriod
      };
      this.api.idWorkDay(obj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.form1.leaveTime = res.data;
        } else {
          this.$Message.error(res.msg);
        }
      });
    },

    //提交
    handleSubmit(name) {
      this.form1.endDate = new Date(this.form1.endDate)
      this.$refs[name].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          let dat = new Date(this.form1.startDate).toJSON();
          let date = new Date(+new Date(dat) + 8 * 3600 * 1000).toISOString();
          let d1 = new Date(this.form1.endDate).toJSON();
          let date1 = new Date(+new Date(d1) + 8 * 3600 * 1000).toISOString();
          console.log(date,date1);
          let obj = {
            detail: this.form1.leaveType,
            duration: this.form1.leaveTime,
            startTime: date,
            startTimeSolt: this.form1.startDatePeriod,
            endTime: date1,
            endTimeSolt: this.form1.endDatePeriod,
            reason: this.form1.leaveReason,
            applyNo: this.applyNo,
            uid: "1"
          };
          console.log(obj);
          // 删除文件
          if (this.deleteFiles.length > 0) {
            this.deleteFiles.forEach(element => {
              if (element.id) {
                let obj = {
                  id: element.id
                };
                this.api.deleteAttachment(obj).then(res => {
                  if (res.code == 200) {
                  } else {
                    this.$Message.error(res.msg);
                    return false;
                  }
                });
              }
            });
          }
          // 请假提交
          this.api.addVacate(obj).then(res => {
            if (res.code == 200 && res.data != null) {
              if (res.data.applyNo) {
                this.$refs.upload.applyNo = res.data.applyNo;
                this.applyNo = res.data.applyNo;
              } else {
                this.$Message.error("文件上传失败");
              }
              this.upload();
            } else {
              this.submitLoading = false;
              this.$Message.error(res.msg);
            }
          });
        } else {
          this.$Message.error("信息填写有误");
        }
      });
    },

    // 回退到上一步
    previousStep() {
      this.$emit("currentChanged", "0");
    },

    // 请假类型改变
    leaveTypeChange(name) {
      let noticeMsg = new Map([
        ["3", ["病假", "按照公司《考勤与休假管理办法》执行", 6.8]],
        [
          "4",
          [
            "婚假",
            "3天（男性年满25周岁、女性年满23周岁增加10天）。结婚证登记日期一年内休完，可分2次申请。",
            6.8
          ]
        ],
        [
          "5",
          [
            "丧假",
            "公司给予4天丧假，往返超过1000公里增加1天，往返超过2000公里增加2天（最多不超过3天）",
            6.8
          ]
        ],
        ["6", ["工伤假", "按照公司《考勤与休假管理办法》执行", 6.8]],
        ["7", ["民族假", "按国家民委确定的法定民族假日执行", 6.8]],
        [
          "8",
          [
            "孕检假",
            "符合国家生育政策的，妊娠28周以内每月检查一次；28周致32周，每两周检查一次； 32周以上每周检查一次。每次给假半天",
            6.8
          ]
        ],
        [
          "9",
          [
            "产假",
            "符合国家生育政策的，<24周岁98天（难产113天）；>=24周岁128天（难产143天）；妊娠4个月以上流产42天（不足4个月15天）；多胞胎（双胞胎及以上）每多一胎增加15天。",
            6.8
          ]
        ],
        ["10", ["哺乳假", "婴儿一周岁以内，每天1小时", 6.8]],
        ["11", ["陪护假", "按照国家生育政策，每人10天，一次休完", 6.8]]
      ]);
      if (name !== undefined) {
        this.usableDays(name);
        // 年休假和事假提示剩余天数
        if (name == 1 || name == 2 || name == 20) {
          this.leaveTypeShow = true;
        } else {
          // 提示相关请假信息
          let notice = noticeMsg.get(name);
          this.$Notice.open({
            title: notice[0],
            desc: false ? "" : notice[1],
            duration: notice[2]
          });
          this.leaveTypeShow = false;
        }
      } else {
        this.leaveTypeShow = false;
      }
    },

    // 保存需要上传的文件
    handleUpload(file) {
      let keyID = Math.random()
        .toString()
        .substr(2); // 16位前端标志id
      file["keyID"] = keyID;
      this.file.push(file);
      return false;
    },

    // 删除文件
    delectFile(keyID) {
      this.file = this.file.filter(item => {
        if (item.keyID == keyID) {
          // 保存到删除文件数组
          if (item.id) {
            this.deleteFiles.push(item);
          }
        }
        return item.keyID != keyID;
      });
    },
    // 上传文件
    upload() {
      this.$refs.upload.headers.Authorization = sessionStorage.getItem(
        "credentials"
      );
      if (this.file.length > 0) {
        for (let i = 0; i < this.file.length; i++) {
          let item = this.file[i];
          // 重新提交原文件不上传
          if (item.id) {
            this.fileIndex++;
            // 如果全部是原文件
            if (this.fileIndex == this.file.length) {
              this.submitLoading = false;
              this.file = [];
              this.$Message.success("请假申请提交成功");
              // 向父组件传递事件
              this.$emit("currentChanged", "2");
              // 向父组件传递applyNo查询审批流程
              this.$emit("currentChanged", this.applyNo);
            }
          } else {
            this.$refs.upload.post(item);
          }
        }
      } else {
        this.submitLoading = false;
        this.$Message.success("请假申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
    },
    // 文件上传成功
    uploadSuccess(response, file, fileList) {
      this.fileIndex++;
      this.$Message.success(response.data[0].name + "上传成功");
      if (this.fileIndex == this.file.length) {
        this.submitLoading = false;
        this.file = [];
        this.$Message.success("请假申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
      return true;
    },

    // 文件上传失败
    uploadFail(response, file, fileList) {
      this.fileIndex++;
      this.$Message.error(response.data[0].name + "上传失败");
      if (this.fileIndex == this.file.length) {
        this.submitLoading = false;
        this.file = [];
        this.$Message.success("请假申请提交成功");
        // 向父组件传递事件
        this.$emit("currentChanged", "2");
        // 向父组件传递applyNo查询审批流程
        this.$emit("currentChanged", this.applyNo);
      }
      return false;
    },

    // 填充表单
    formFill() {
      if (this.applyInfo != null) {
        this.previousStepShow = false;
        this.applyNo = this.applyInfo.applyNo;
        let obj = {
          applyNo: this.applyInfo.applyNo
        };

        this.api.getApplyInfo(obj).then(res => {
          if (res.code == 200 && res.data != null) {
            const leave = new Map([
              ["年休假", 1],
              ["事假", 2],
              ["病假", 3],
              ["婚假", 4],
              ["丧假", 5],
              ["工伤假", 6],
              ["民族假", 7],
              ["孕检假", 8],
              ["产假", 9],
              ["哺乳假", 10],
              ["陪护假", 11]
            ]);
            let leaveType = leave.get(res.data.detail);
            this.form1.leaveType = leaveType + "";
            this.leaveTypeShow = true;
            // 获取休假天数
            this.usableDays(leaveType);
            this.form1.startDate = res.data.startTime.substr(0, 10);
            this.form1.startDatePeriod =
              res.data.startTime.substr(11, 4) == "上午" ? "am" : "pm";
            this.form1.endDate = res.data.endTime.substr(0, 10);
            this.form1.endDatePeriod =
              res.data.endTime.substr(11, 4) == "上午" ? "am" : "pm";
            // 计算时间
            this.checkLeaveTime();
            // 理由和文件不是必填
            if (res.data.reason) {
              this.form1.leaveReason = res.data.reason;
            }
            if (res.data.uerAttachment.length > 0) {
              res.data.uerAttachment.forEach(element => {
                let file = {
                  id: element.id,
                  name: element.fileName
                };
                this.handleUpload(file);
              });
            }
          } else {
            this.$Message.error(res.msg);
          }
        });
      }
    }
  },
  mounted() {
    this.selectType();
    // 填充表单
    this.formFill();
  },
  beforeDestroy() {
    // validateStartDate = null;
    // validateEndDate = null;
    // validateLeaveTime = null;
    this.form1 = null;
    this.rules1 = null;
    this.leaveTypeList = null;
    this.leaveTypeValue = null;
    this.usableDay = null;
    this.file = null;
    this.deleteFiles = null;
    this.applyNo = null;
    this.previousStepShow = null;
    this.leaveTypeShow = null;
    this.fileIndex = null;
    this.submitLoading = null;
    this.action = null;
  }
};
</script>

<style lang="less" scoped>
@import "./index";
</style>

<style>
textarea.ivu-input {
  resize: none;
}
</style>